package com.zenithmind.mall.pojo.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.zenithmind.common.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 百亿补贴商品实体 - 遵循单一职责原则，专门管理补贴商品信息
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("mall_subsidy_product")
public class SubsidyProduct extends BaseEntity {

    /**
     * 补贴活动ID
     */
    private String activityId;

    /**
     * 商品ID
     */
    private String productId;

    /**
     * 补贴后价格
     */
    private BigDecimal subsidyPrice;

    /**
     * 原价
     */
    private BigDecimal originalPrice;

    /**
     * 补贴金额
     */
    private BigDecimal subsidyAmount;

    /**
     * 补贴比例
     */
    private BigDecimal subsidyRate;

    /**
     * 最大补贴金额
     */
    private BigDecimal maxSubsidyAmount;

    /**
     * 补贴库存（参与补贴的商品数量）
     */
    private Integer subsidyStock;

    /**
     * 已补贴数量
     */
    private Integer subsidizedCount;

    /**
     * 每用户限购数量
     */
    private Integer limitPerUser;

    /**
     * 补贴开始时间
     */
    private LocalDateTime startTime;

    /**
     * 补贴结束时间
     */
    private LocalDateTime endTime;

    /**
     * 状态（0-未开始，1-进行中，2-已结束，3-已售罄）
     */
    private Integer status;

    /**
     * 优先级
     */
    private Integer priority;

    /**
     * 是否启用（0-禁用，1-启用）
     */
    private Integer enabled;

    /**
     * 补贴标签
     */
    private String subsidyLabel;

    /**
     * 排序号
     */
    private Integer sortOrder;

    // 业务方法

    /**
     * 检查是否未开始
     */
    public boolean isNotStarted() {
        return Objects.equals(this.status, 0);
    }

    /**
     * 检查是否进行中
     */
    public boolean isActive() {
        return Objects.equals(this.status, 1);
    }

    /**
     * 检查是否已结束
     */
    public boolean isEnded() {
        return Objects.equals(this.status, 2);
    }

    /**
     * 检查是否已售罄
     */
    public boolean isSoldOut() {
        return Objects.equals(this.status, 3);
    }

    /**
     * 检查是否启用
     */
    public boolean isEnabled() {
        return Objects.equals(this.enabled, 1);
    }

    /**
     * 检查是否在补贴时间范围内
     */
    public boolean isInSubsidyTime() {
        LocalDateTime now = LocalDateTime.now();
        return (startTime == null || !now.isBefore(startTime)) &&
               (endTime == null || !now.isAfter(endTime));
    }

    /**
     * 检查是否可以享受补贴
     */
    public boolean canSubsidy() {
        return isEnabled() && isActive() && isInSubsidyTime() && hasSubsidyStock();
    }

    /**
     * 检查是否有补贴库存
     */
    public boolean hasSubsidyStock() {
        return getRemainingSubsidyStock() > 0;
    }

    /**
     * 获取剩余补贴库存
     */
    public Integer getRemainingSubsidyStock() {
        if (subsidyStock == null) {
            return Integer.MAX_VALUE; // 无限制
        }
        int total = subsidyStock;
        int used = subsidizedCount != null ? subsidizedCount : 0;
        return Math.max(0, total - used);
    }

    /**
     * 检查用户是否可以购买指定数量
     */
    public boolean canBuy(Integer quantity) {
        if (quantity == null || quantity <= 0) {
            return false;
        }
        
        // 检查限购数量
        if (limitPerUser != null && quantity > limitPerUser) {
            return false;
        }
        
        // 检查补贴库存
        return getRemainingSubsidyStock() >= quantity;
    }

    /**
     * 使用补贴库存
     */
    public boolean useSubsidyStock(Integer quantity) {
        if (!canBuy(quantity)) {
            return false;
        }
        
        this.subsidizedCount = (this.subsidizedCount != null ? this.subsidizedCount : 0) + quantity;
        
        // 检查是否售罄
        if (getRemainingSubsidyStock() <= 0) {
            this.status = 3; // 已售罄
        }
        
        return true;
    }

    /**
     * 计算实际补贴金额
     */
    public BigDecimal calculateActualSubsidyAmount() {
        if (subsidyAmount != null) {
            return subsidyAmount;
        }
        
        if (originalPrice != null && subsidyPrice != null) {
            return originalPrice.subtract(subsidyPrice);
        }
        
        if (originalPrice != null && subsidyRate != null) {
            BigDecimal calculated = originalPrice.multiply(subsidyRate);
            if (maxSubsidyAmount != null && calculated.compareTo(maxSubsidyAmount) > 0) {
                return maxSubsidyAmount;
            }
            return calculated;
        }
        
        return BigDecimal.ZERO;
    }

    /**
     * 计算折扣率
     */
    public BigDecimal getDiscountRate() {
        if (originalPrice == null || originalPrice.compareTo(BigDecimal.ZERO) <= 0 ||
            subsidyPrice == null || subsidyPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        
        return originalPrice.subtract(subsidyPrice)
                          .divide(originalPrice, 2, java.math.RoundingMode.HALF_UP);
    }

    /**
     * 开始补贴
     */
    public void startSubsidy() {
        if (isNotStarted() && isEnabled()) {
            this.status = 1;
        }
    }

    /**
     * 结束补贴
     */
    public void endSubsidy() {
        if (isActive()) {
            this.status = 2;
        }
    }

    /**
     * 获取状态名称
     */
    public String getStatusName() {
        if (status == null) return "未知";
        
        switch (status) {
            case 0: return "未开始";
            case 1: return "进行中";
            case 2: return "已结束";
            case 3: return "已售罄";
            default: return "未知";
        }
    }

    /**
     * 计算补贴剩余时间（秒）
     */
    public Long getRemainingSeconds() {
        if (endTime == null) {
            return null;
        }
        
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(endTime)) {
            return 0L;
        }
        
        return java.time.Duration.between(now, endTime).getSeconds();
    }

    /**
     * 计算距离开始时间（秒）
     */
    public Long getSecondsToStart() {
        if (startTime == null) {
            return null;
        }
        
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(startTime)) {
            return 0L;
        }
        
        return java.time.Duration.between(now, startTime).getSeconds();
    }

    /**
     * 获取补贴库存进度百分比
     */
    public Double getSubsidyStockProgress() {
        if (subsidyStock == null || subsidyStock <= 0) {
            return 0.0;
        }
        
        int used = subsidizedCount != null ? subsidizedCount : 0;
        return (double) used / subsidyStock * 100;
    }

    /**
     * 检查是否为热门补贴商品
     */
    public boolean isHotSubsidyProduct() {
        if (subsidyStock == null || subsidyStock <= 0) {
            return false;
        }
        
        // 如果已补贴数量超过总库存的50%，认为是热门商品
        int used = subsidizedCount != null ? subsidizedCount : 0;
        return (double) used / subsidyStock >= 0.5;
    }

    /**
     * 验证补贴商品数据完整性
     */
    public boolean isValid() {
        return activityId != null && !activityId.trim().isEmpty() &&
               productId != null && !productId.trim().isEmpty() &&
               subsidyPrice != null && subsidyPrice.compareTo(BigDecimal.ZERO) > 0 &&
               originalPrice != null && originalPrice.compareTo(BigDecimal.ZERO) > 0 &&
               subsidyPrice.compareTo(originalPrice) <= 0 &&
               status != null && status >= 0 && status <= 3 &&
               enabled != null;
    }
}
